<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>提醒功能授权</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="${ctx}/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="${ctx}/systemStatic/style/admin.css">
    <link rel="stylesheet" href="${ctx}/iconfont/iconfont.css"/>
    <link rel="stylesheet" href="${ctx}/css/public.css">
    <script type="text/javascript">
        var __ctx = "${ctx}";
    </script>
</head>
<body>

<form class="layui-form" style="margin: 15px;" lay-filter="sysPopupRemindDataForm">
    <div class="bpmAuthorizeAddUser" style="height: 485px;">
        <table id="selectAuthorizeUser" lay-filter="selectAuthorizeUser"></table>
    </div>
    <div class="layui-form-item">
        <div style="text-align: center;">
            <a lay-submit lay-filter="sysPopupRemind" class="layui-btn btn-n">提交</a>
            <a id="closeWindow" class="layui-btn layui-btn-danger">返回</a>
        </div>
    </div>
</form>

<script type="text/html" id="bar">
    <div class="row-bar">
        <input type="hidden" id="names1">
        <a class="layui-btn layui-btn-xs" lay-event="select">选择</a>
        <a class="layui-btn layui-btn-xs" lay-event="reset">重置</a>
    </div>
</script>
<script type="text/html" id="toolbar">
    <div class="selectToolbar">
        <label style="float: left;"><b>允许所有人访问</b></label>
        <div class="layui-input-block">
            <input type="checkbox" name="switch" lay-skin="switch" lay-text="是|否" lay-filter="allowAll" id="allowAllUser">
        </div>
    </div>
</script>
<script src="${ctx}/public/component.js" type="text/javascript"></script>
<script src="${ctx}/layui/layui.js"></script>
<script>

    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','common','jquery','commons','form','setter','layer','table'], function () {
        var $ = layui.jquery;
        var commons = layui.commons;
        var form = layui.form;
        var setter = layui.setter;
        var common = layui.common;
        var layer = layui.layer;
        var table = layui.table;

        var objType = "${objType}";
        var popupId = "${id}";

        //关闭当前页面
        $("#closeWindow").click(function () {
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        });

        // 回显已选的授权用户列表数据
        if(!layui.defaultAuthorizeUserTableData) layui.defaultAuthorizeUserTableData = [];
        var allowAllUserData = [{rightType:'all', rightTypeName: '所有用户', ownerList:[{ownerId: '0',ownerName: 'all'}]}];
        layui.allowAllUsersFlag = false;

        layui.selectAuthorizeUserTableData = [
            {rightType: 'user', rightTypeName: '用户授权', ownerList: []}
            , {rightType: 'role', rightTypeName: '角色授权', ownerList: []}
            // , {rightType: 'publicRole', rightTypeName: '公共角色授权', ownerList: []}
            , {rightType: 'org', rightTypeName: '组织授权', ownerList: []}
            // , {rightType: 'position', rightTypeName: '岗位授权', ownerList: []}
        ];

        function getIndexOfUsersByRightType(type){
            var i = 0;
            for(;i<layui.selectAuthorizeUserTableData.length;i++){
                if(layui.selectAuthorizeUserTableData[i].rightType === type) break;
            }
            return i;
        }

        layui.each(layui.defaultAuthorizeUserTableData,function(index,item){
            if(item.rightType === 'all') {
                layui.allowAllUsersFlag = true;
                return false;
            }
            layui.selectAuthorizeUserTableData[getIndexOfUsersByRightType(item.rightType)].ownerList = item.ownerList;
        });

        form.on('switch(allowAll)', function(data){
            if(data.elem.checked){
                $(".auth-user").hide();
                $(".row-bar").hide();
                layui.allowAllUsersFlag = true;
            }else{
                $(".auth-user").show();
                $(".row-bar").show();
                layui.allowAllUsersFlag = false;
            }
        });

        var selectAuthorizeUserTable = table.render({
            elem: '#selectAuthorizeUser',
            toolbar: '#toolbar',
            cols: [[
                {field: 'rightTypeName', title: '权限分类', width:180, align: 'center'}
                ,{field: 'ownerList', title: '授权给', align: 'center', templet: function(d){
                    var html = '';
                    var user = d.ownerList;
                    var rightType = d.rightType;
                    layui.each(user, function(index,item){
                        if(rightType == 'user'){
                            html += '<a href="javascript:void(0);" class=" auth-user" style="color: blue;margin-right: 5px;" onclick=onAuthUserClick("'+ item.ownerId +'")>'+ item.ownerName +'</a>';
                        }else{
                            html += '<span class=" auth-user" style="margin-right: 5px;">'+ item.ownerName +'</span>';
                        }
                    });
                    return html;

                }
                }
                ,{title: '操作', width:120, toolbar: '#bar', align: 'center'}
            ]],
            data: layui.selectAuthorizeUserTableData
        });



        // 表格行工具监听
        table.on('tool(selectAuthorizeUser)',function(obj){
            switch (obj.event) {
                case 'select':
                    switch (obj.data.rightType) {
                        case 'user':
                            openSysUserSelectorWin();
                            break;
                        case 'role':
                            openRoleSelectorWin();
                            break;
                        case 'org':
                            openOrgSelectorWin();
                            break;
                    }
                    break;
                case 'reset':
                    switch (obj.data.rightType) {
                        case 'user':
                            layui.selectAuthorizeUserTableData[0].ownerList = [];
                            selectAuthorizeUserTable.reload({data:layui.selectAuthorizeUserTableData});
                            break;
                        case 'role':
                            layui.selectAuthorizeUserTableData[1].ownerList = [];
                            selectAuthorizeUserTable.reload({data:layui.selectAuthorizeUserTableData});
                            break;
                        case 'org':
                            layui.selectAuthorizeUserTableData[2].ownerList = [];
                            selectAuthorizeUserTable.reload({data:layui.selectAuthorizeUserTableData});
                            break;
                    }
                    break;
            }
        });

        // 弹出“人员选择器”
        function openSysUserSelectorWin(){
            var userSelectorWin;
            parent.layer.open({
                type: 2,
                title: '用户选择器',
                btn:["保存","取消","撤销"],
                area: ['980px','600px'],
                resize:false,
                content: serverPath.systemPath + setter.sysLinkPath + "dialog/view/sysUserDialog",
                success: function(layero, index){
                    body = parent.layer.getChildFrame('body',index);
                    userSelectorWin = parent.window[layero.find('iframe')[0]['name']];
                    if(layui.selectAuthorizeUserTableData[0].ownerList.length > 0){
                        userSelectorWin.layui.userList = initUserList();
                    }
                },
                yes:function(index,layero){
                    layui.selectAuthorizeUserTableData[0].ownerList = [];
                    //用户选择器返回的选择人员数组[{name:"name1",userId:"userId1"},{name:"name2",userId:"userId2"}...]
                    var theUserList = body.find("input[name=userList]").val();
                    if (theUserList){
                        layui.each(JSON.parse(theUserList),function(index,item){
                            layui.selectAuthorizeUserTableData[0].ownerList.push({ownerId:item.userId,ownerName:item.name});
                        });
                        selectAuthorizeUserTable.reload({data:layui.selectAuthorizeUserTableData});
                        parent.layer.close(index);
                    }
                },
                btn3:function(index, layero){
                    userSelectorWin.cancelData(index);
                    return false //开启该代码可禁止点击该按钮关闭
                }
            });
        }
        // 给“人员选择器”初始化userList
        function initUserList(){
            return $.map(layui.selectAuthorizeUserTableData[0].ownerList,function(v){
                return {name:v.ownerName,userId:v.ownerId};
            })
        }

        // 弹出“角色选择器”
        function openRoleSelectorWin(){
            var roleSelectorWin;
            var body;
            parent.layer.open({
                type: 2,
                title: '角色选择器',
                btn:["保存","取消","撤销"],
                area: ['980px','600px'],
                resize:false,
                content: serverPath.systemPath + setter.sysLinkPath + "dialog/view/sysRoleDialog",
                success: function(layero, index){
                    body = parent.layer.getChildFrame('body',index);
                    roleSelectorWin = parent.window[layero.find('iframe')[0]['name']];
                    if(layui.selectAuthorizeUserTableData[1].ownerList.length > 0){
                        roleSelectorWin.layui.roleList = initRoleList();
                    }
                },
                yes: function(index,layero){
                    layui.selectAuthorizeUserTableData[1].ownerList = [];
                    //用户选择器返回的选择人员数组[{name:"name1",userId:"userId1"},{name:"name2",userId:"userId2"}...]
                    var theUserList = body.find("input[name=roleList]").val();
                    if (theUserList){
                        layui.each(JSON.parse(theUserList),function(index,item){
                            layui.selectAuthorizeUserTableData[1].ownerList.push({ownerId: item.roleId,ownerName: item.name});
                        });
                        selectAuthorizeUserTable.reload({data:layui.selectAuthorizeUserTableData});
                        parent.layer.close(index);
                    }
                },
                btn3:function(index, layero){
                    roleSelectorWin.cancelData(index);
                    return false //开启该代码可禁止点击该按钮关闭
                }
            });
        }
        // 给“角色选择器”初始化roleList
        function initRoleList(){
            return $.map(layui.selectAuthorizeUserTableData[1].ownerList,function(v){
                return {name:v.ownerName,roleId:v.ownerId};
            })
        }
        // 弹出“公共角色选择器”
        function openPublicRoleSelectorWin(){
            var publicRoleSelectorWin = null;
            parent.layer.open({
                type: 2,
                title: '公共角色选择器',
                area: ['980px','600px'],
                resize:false,
                content: '',
                success: function(layero, index){
                    publicRoleSelectorWin = parent.window[layero.find('iframe')[0]['name']];
                },
                end: function(){

                }
            });
        }
        // 弹出“组织选择器”
        function openOrgSelectorWin(){
            var body;
            var orgSelectorWin;
            parent.layer.open({
                type: 2,
                title: '组织选择器',
                btn:["保存","取消","撤销"],
                area: ['980px','600px'],
                resize:false,
                content: serverPath.systemPath + setter.sysLinkPath + "dialog/view/sysOrgDialog",
                success: function(layero, index){
                    body = parent.layer.getChildFrame('body',index);
                    orgSelectorWin = parent.window[layero.find('iframe')[0]['name']];
                    if(layui.selectAuthorizeUserTableData[2].ownerList.length > 0){
                        orgSelectorWin.layui.orgList = initOrgList();
                    }
                },
                yes: function(index, layero){
                    layui.selectAuthorizeUserTableData[2].ownerList = [];
                    //用户选择器返回的选择人员数组[{name:"name1",userId:"userId1"},{name:"name2",userId:"userId2"}...]
                    var theUserList = body.find("input[name=orgList]").val();
                    if (theUserList){
                        layui.each(JSON.parse(theUserList),function(index,item){
                            layui.selectAuthorizeUserTableData[2].ownerList.push({ownerId: item.orgId,ownerName: item.name});
                        });
                        selectAuthorizeUserTable.reload({data:layui.selectAuthorizeUserTableData});
                        parent.layer.close(index);
                    }
                },
                btn3:function(index, layero){
                    roleSelectorWin.cancelData(index);
                    return false //开启该代码可禁止点击该按钮关闭
                }
            });
        }
        // 给“组织选择器”初始化orgList
        function initOrgList(){
            return $.map(layui.selectAuthorizeUserTableData[2].ownerList,function(v){
                return {name:v.ownerName,orgId:v.ownerId};
            })
        }
        // 弹出“岗位选择器”
        function openPositionSelectorWin(){
            var positionSelectorWin = null;
            parent.layer.open({
                type: 2,
                title: '岗位选择器',
                area: ['980px','600px'],
                resize:false,
                content: '',
                success: function(layero, index){
                    positionSelectorWin = parent.window[layero.find('iframe')[0]['name']];
                },
                end: function(){

                }
            });
        }

        // 点击授权人员弹窗
        window.onAuthUserClick = function(ownerId){
            parent.layer.open({
                type: 2,
                title: '人员详细信息',
                area: ['938px', '620px'],
                content: serverPath.systemPath + setter.sysLinkPath + 'sysUser/view/view?userId=' + ownerId
            });
        };

        if(layui.allowAllUsersFlag){
            $("input[name='switch']").attr("checked",true);
            form.render("checkbox");
            layui.selectAuthorizeUserTableData[0].ownerList = [];
            layui.selectAuthorizeUserTableData[1].ownerList = [];
            layui.selectAuthorizeUserTableData[2].ownerList = [];
            $(".row-bar").hide();
        }

        var index = parent.layer.getFrameIndex(window.name);
        form.on("submit(sysPopupRemind)",function () {
            var userList = layui.selectAuthorizeUserTableData[0].ownerList;
            var userRights = layui.selectAuthorizeUserTableData[0].rightType;

            var roleList = layui.selectAuthorizeUserTableData[1].ownerList;
            var roleRights = layui.selectAuthorizeUserTableData[1].rightType;

            var orgList = layui.selectAuthorizeUserTableData[2].ownerList;
            var orgRights = layui.selectAuthorizeUserTableData[2].rightType;

            var userIdListToArray = "";
            var userNameListToArray = "";
            if(userList != null){
                for(var i= 0;i <userList.length;i++){
                    userIdListToArray+=userList[i].ownerId+",";
                }
                for(var i= 0;i <userList.length;i++){
                    userNameListToArray+=userList[i].ownerName+",";
                }
            }
            var roleIdListToArray = "";
            var roleNameListToArray = "";
            if(userList != null){
                for(var i= 0;i <roleList.length;i++){
                    roleIdListToArray+= roleList[i].ownerId+",";
                }
                for(var i= 0;i <roleList.length;i++){
                    roleNameListToArray+= roleList[i].ownerName+",";
                }
            }
            var orgIdListToArray = "";
            var orgNameListToArray = "";
            if(orgList != null){
                for(var i= 0;i <orgList.length;i++){
                    orgIdListToArray+=orgList[i].ownerId + ",";
                }
                for(var i= 0;i <orgList.length;i++){
                    orgNameListToArray+=orgList[i].ownerName + ",";
                }
            }

            var switchAll = layui.allowAllUsersFlag;
            var sysObjRights = [];
            if(switchAll){
                var allRight = {};
                allRight.objectId = popupId;
                allRight.objType = objType;
                allRight.rightType = 'all';
                allRight.ownerId = '1';
                allRight.switchAll = switchAll;
                sysObjRights.push(allRight);
            }else{
                for(var i= 0;i <userList.length;i++){
                    var user = {};
                    user.objectId = popupId;
                    user.objType = objType;
                    user.rightType = userRights;
                    user.ownerName = userList[i].ownerName;
                    user.ownerId = userList[i].ownerId;
                    user.switchAll = switchAll;
                    sysObjRights.push(user);
                }
                for(var i= 0;i <roleList.length;i++){
                    var role = {};
                    role.objectId = popupId;
                    role.objType = objType;
                    role.rightType = roleRights;
                    role.ownerName = roleList[i].ownerName;
                    role.ownerId = roleList[i].ownerId;
                    role.switchAll = switchAll;
                    sysObjRights.push(role);
                }
                for(var i= 0;i <orgList.length;i++){
                    var org = {};
                    org.objectId = popupId;
                    org.objType = objType;
                    org.rightType = orgRights;
                    org.ownerName = orgList[i].ownerName;
                    org.ownerId = orgList[i].ownerId;
                    org.switchAll = switchAll;
                    sysObjRights.push(org);
                }
            }
            if(sysObjRights.length == 0){
                var noRights = {};
                noRights.objectId = popupId;
                sysObjRights.push(noRights);
            }
            var data = JSON.stringify(sysObjRights);
            $.ajax({
                url:serverPath.systemPath + setter.sysLinkPath + 'sysPopupRemind/saveRights',
                type:'post',
                dataType:'json',
                contentType:"application/json;charset=utf-8",
                data:data,
                success : function (data) {
                    if(commons._filterRecord(data)){
                        layer.alert(data.msg,function () {
                            parent.location.href = serverPath.systemPath+setter.sysLinkPath+'sysPopupRemind/view/list' ;
                            layer.close(index);
                        });
                    }else{
                        layer.msg(data.msg);
                    }
                    return false;
                },
                error : function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("保存失败！" + XMLHttpRequest.status);
                }
            });
        })

    });
</script>
</body>
</html>